package com.example.suuu.tools.excel;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelReader;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.excel.read.metadata.ReadSheet;
import com.alibaba.excel.write.handler.SheetWriteHandler;
import com.alibaba.excel.write.metadata.style.WriteCellStyle;
import com.alibaba.excel.write.style.HorizontalCellStyleStrategy;
import com.example.suuu.config.exception.AppException;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

public class ExcelUtils {
    /**
     * 生成文件流
     *
     * @param dataList          数据
     * @param response          请求头
     * @param model             实体
     * @param autoCloseStream
     * @param sheetWriteHandler 下拉
     */
    public static void download(List dataList, HttpServletResponse response, Class<?> model, Boolean autoCloseStream, SheetWriteHandler sheetWriteHandler) {
        try {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
            String format = sdf.format(new Date());
            WriteCellStyle headWriteCellStyle = new WriteCellStyle();
            //设置头居中
            headWriteCellStyle.setHorizontalAlignment(HorizontalAlignment.CENTER);
            //内容策略
            WriteCellStyle contentWriteCellStyle = new WriteCellStyle();
            //设置 水平居中
            contentWriteCellStyle.setHorizontalAlignment(HorizontalAlignment.LEFT);
            HorizontalCellStyleStrategy horizontalCellStyleStrategy = new HorizontalCellStyleStrategy(headWriteCellStyle, contentWriteCellStyle);
            response.setContentType("application/vnd.ms-excel;charset=utf-8");
            //response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            response.setCharacterEncoding("utf-8");
            // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
            String fileName = URLEncoder.encode(format, "UTF-8");
            response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xls");
            // 这里需要设置不关闭流
            EasyExcel.write(response.getOutputStream(), model).autoCloseStream(autoCloseStream).registerWriteHandler(horizontalCellStyleStrategy).sheet(format).registerWriteHandler(sheetWriteHandler).doWrite(dataList);

        } catch (IOException e) {
            throw new AppException("生成文件流失败");
        }
    }


    /**
     * 导入数据
     * @param file          文件
     * @param model         实体
     * @param analysisEventListener     监听
     */
    public static void importExcel(MultipartFile file, Class<?> model, AnalysisEventListener<?> analysisEventListener) {
        ExcelReader excelReader = null;
        InputStream inputStream = null;
        //获取文件名
        String fileName = file.getOriginalFilename();
        //获取文件类型
        String fileType = "";
        if (fileName != null) {
            fileType = fileName.substring(fileName.lastIndexOf(".") + 1);
        }
        //判断是否是excel格式的文件
        if ("xlsx".equals(fileType) || "xls".equals(fileType)) {
            try {
                inputStream = file.getInputStream();
                excelReader = EasyExcel.read(inputStream, model,
                        analysisEventListener).build();
                ReadSheet readSheet = EasyExcel.readSheet(0).build();
                excelReader.read(readSheet);

            } catch (IOException e) {
                throw new AppException("导入失败");
            } finally {
                try {
                    inputStream.close();
                } catch (IOException ioe) {
                    throw new AppException("导入失败");
                }
                // 这里一定别忘记关闭，读的时候会创建临时文件
                if (excelReader != null) {
                    excelReader.finish();
                }
            }
        } else {
            throw new AppException("文件格式错误");
        }
    }
}
